#!/usr/bin/perl

##### Library ########################################################
use File::Temp qw/ tempfile tempdir /;


##### Global ########################################################
my $SYSTEM_FILE_PATH = "/System/Library/CoreServices/SystemVersion.plist";
my $SYSTEM_FILE_OS_VERSION_KEY = "ProductVersion";
my $OS_MAJOR_VERSION_INDEX = 2;
my $OS_MINOR_VERSION_INDEX = 3;


##### Private Functions ########################################################
sub getOSVersionString
{
    my $oldSeperator;
    my $plistData;
    my @items;
    my $item;
    my $versiondata;

    # if there's no THERE there, we return FALSE
    if (! -e $SYSTEM_FILE_PATH) {
        return ();
    }

    $oldSeperator = $/;
    $/ = \0;

    # open file, then get version string
    open( PLIST, $SYSTEM_FILE_PATH) || do {
        return ();
    };

    $plistData = <PLIST>;
    $plistData =~ /<dict>(.*?)<\/dict>/gis;

    @items = split(/<key>/, $plistData);

    shift @items;
    foreach $item (@items) {
        $item =~ /(.*?)<\/key>.*?<string>(.*?)<\/string>/gis;
        $versiondata{ $1 } = $2;
    }

    close(PLIST);

    $/ = $oldSeperator;
    
    return $versiondata{$SYSTEM_FILE_OS_VERSION_KEY};
}

sub getOSVersionElement
{
    my $versionString;
    my @versionElements;
    my $elementsCount;
    my $elementIndex = $_[0];

    $versionString = getOSVersionString();
    if ( ! defined($versionString) ) {
    	return ();
    }

    @versionElements = split(/\./, $versionString);
    $elementsCount   = @versionElements;
	if ( $elementsCount >= $elementIndex ) {
        return $versionElements[$elementIndex - 1];
	}
	else {
    	return ();
	}
}


##### Public Functions ########################################################
# return OS major version (ex. return "6" if Mac OS X 10.6.2)
sub BRUtilityGetOSMajorVersion
{
	return getOSVersionElement($OS_MAJOR_VERSION_INDEX);
}

# return OS minor version (ex. return "2" if Mac OS X 10.6.2)
sub BRUtilityGetOSMinorVersion
{
	return getOSVersionElement($OS_MINOR_VERSION_INDEX);
}

1;